package com.github.sbb.sherry.primitives.rules.jexl;

import com.github.sbb.sherry.primitives.api.Action;
import com.github.sbb.sherry.primitives.api.Condition;
import com.github.sbb.sherry.primitives.api.Facts;
import com.github.sbb.sherry.primitives.core.BasicRule;
import java.util.Objects;
import org.apache.commons.jexl3.JexlBuilder;
import org.apache.commons.jexl3.JexlEngine;


public class JexlRule extends BasicRule {

  static final JexlEngine DEFAULT_JEXL = new JexlBuilder().cache(128).create();

  private Condition condition = Condition.FALSE;
  private Action action;
  private final JexlEngine jexl;

  public JexlRule(String name) {
    this(name, DEFAULT_JEXL);
  }

  public JexlRule(String name, JexlEngine jexl) {
    super(name);
    this.jexl = Objects.requireNonNull(jexl, "jexl cannot be null");
  }

  public JexlRule condition(String condition) {
    Objects.requireNonNull(condition, "condition cannot be null");
    this.condition = new JexlCondition(condition, jexl);
    return this;
  }

  public JexlRule action(String action) {
    Objects.requireNonNull(action, "action cannot be null");
    this.action = new JexlAction(action, jexl);
    return this;
  }

  public JexlRule priority(int priority) {
    this.priority = priority;
    return this;
  }

  @Override
  public boolean evaluate(Facts facts) {
    Objects.requireNonNull(facts, "facts cannot be null");
    return condition.evaluate(facts);
  }

  @Override
  public void execute(Facts facts) throws Exception {
    Objects.requireNonNull(facts, "facts cannot be null");
    action.execute(facts);
  }

}
